package com.cairenhui.trust.auto.task.runnable;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cairenhui.trust.auto.task.dao.AppointmentBookingMapper;
import com.cairenhui.trust.auto.task.dao.BaseSysUserMapper;
import com.cairenhui.trust.auto.task.dao.VideoWitnessOrderMapper;
import com.cairenhui.trust.auto.task.dao.VwCustomerInfoMapper;
import com.cairenhui.trust.auto.task.model.AppointmentBooking;
import com.cairenhui.trust.auto.task.model.AppointmentBookingExample;
import com.cairenhui.trust.auto.task.model.BaseSysUser;
import com.cairenhui.trust.auto.task.model.BaseSysUserExample;
import com.cairenhui.trust.auto.task.model.CrmOrderInfoV;
import com.cairenhui.trust.auto.task.model.VideoWitnessOrder;
import com.cairenhui.trust.auto.task.model.VideoWitnessOrderExample;
import com.cairenhui.trust.auto.task.model.VwCustomerInfo;
import com.cairenhui.trust.auto.task.util.DateUtils;
import com.cairenhui.trust.auto.task.util.SpringBeanFactoryUtils;
import com.cairenhui.trust.auto.task.util.StringUtil;
import com.cairenhui.trust.auto.task.util.constant.ConfigConstants;
import com.cairenhui.trust.auto.task.util.constant.StatusConstants;
import com.cairenhui.trust.auto.task.util.constant.TypeConstants;

/**
 * 
 * @author 黄瑞庆 TODO 开启线程获取订单（合同） 2017年2月27日
 */

public class WitnessOrderFetchRunnable implements Runnable {

	/** self4j */
	private Logger logger = LoggerFactory
			.getLogger(WitnessOrderFetchRunnable.class);
	private static BaseSysUserMapper baseSysUserMapper;
	private static AppointmentBookingMapper appointmentBookingMapper;
	private static VideoWitnessOrderMapper videoWitnessOrderMapper;
	private static VwCustomerInfoMapper vwCustomerInfoMapper;

	static {
		baseSysUserMapper = (BaseSysUserMapper) SpringBeanFactoryUtils
				.getBean("baseSysUserMapper");
		appointmentBookingMapper = (AppointmentBookingMapper) SpringBeanFactoryUtils
				.getBean("appointmentBookingMapper");
		videoWitnessOrderMapper = (VideoWitnessOrderMapper) SpringBeanFactoryUtils
				.getBean("videoWitnessOrderMapper");
		vwCustomerInfoMapper = (VwCustomerInfoMapper) SpringBeanFactoryUtils
				.getBean("vwCustomerInfoMapper");
	}

	/**
	 * 接收同步列表
	 */
	private List<CrmOrderInfoV> runnableList;
	private Map<String, BaseSysUser> mapSysUser;

	// 构造器
	public WitnessOrderFetchRunnable(final List<CrmOrderInfoV> runnableList) {
		this.runnableList = runnableList;
		List<String> mapBorkerNo = new ArrayList<String>();// 代理号
		for (CrmOrderInfoV view : runnableList) {
			mapBorkerNo.add(view.getBrokerCode());
		}
		BaseSysUserExample sysUserExample = new BaseSysUserExample();
		sysUserExample.createCriteria().andEmpNoIn(mapBorkerNo);
		List<BaseSysUser> listSysUser = baseSysUserMapper
				.selectByExample(sysUserExample);
		this.mapSysUser = getSysUserMap(listSysUser);
	}

	@Override
	public void run() {
		logger.info(this.getClass().getSimpleName()
				+ "获取>>>>>>>{},开始获取CRM排队成功预约信息", Thread.currentThread()
				.getName());

		int count = 0;

		for (int i = 0; i < runnableList.size(); i++) {
			try {
				if (saveFetchInfo(runnableList.get(i))) {
					count++;
				}
			} catch (Exception e) {
				logger.error(this.getClass().getSimpleName()
						+ ">>>>>>{},获取CRM排队成功预约信息出错,预约号{},排队成功时间{},错误信息:{}",
						Thread.currentThread().getName(), runnableList.get(i)
								.getReserveNo(), DateUtils
								.getStrDate(runnableList.get(i)
										.getReservationDate(),
										DateUtils.STRDATE_1
												+ DateUtils.HOURS_MINUTES_SECONDS), e
								.getMessage());
			}

		}
		logger.info(this.getClass().getSimpleName()
				+ ">>>>>>{},成功执行条数[{},(总数:{})],结束CRM排队成功预约信息获取", Thread
				.currentThread().getName(), count, runnableList.size());
	}

	private Boolean saveFetchInfo(CrmOrderInfoV crmOrderInfo) {

		if (StringUtils.isEmpty(crmOrderInfo.getReserveNo())) {
			logger.error(this.getClass().getSimpleName()
					+ ">>>>>>{}获取CRM排队成功预约信息出错,预约号:{},排队成功时间:{},错误信息:{}",
					Thread.currentThread().getName(), crmOrderInfo
							.getReserveNo(), DateUtils.getStrDate(
							crmOrderInfo.getReservationDate(),
							DateUtils.STRDATE_1 + DateUtils.HOURS_MINUTES_SECONDS),
					"预约号为空");
			return false;
		}
		if (null == crmOrderInfo.getBrokerCode()
				|| null == mapSysUser.get(crmOrderInfo.getBrokerCode())) {
			logger.error(
					this.getClass().getSimpleName()
							+ ">>>>>>>{},获取CRM排队成功预约信息出错, 预约号:{},排队成功时间:{},客户经理编号:{},错误信息:{}",
					Thread.currentThread().getName(),
					crmOrderInfo.getReserveNo(),
					null != crmOrderInfo.getReservationDate() ? DateUtils
							.getStrDate(crmOrderInfo.getReservationDate(),
									DateUtils.STRDATE_1
											+ DateUtils.HOURS_MINUTES_SECONDS) : "",
					null != crmOrderInfo.getBrokerCode() ? crmOrderInfo.getBrokerCode() : "",
					"客户经理编号为空或未有该客户经理");
			return false;
		}

		AppointmentBooking booking = new AppointmentBooking();
		VideoWitnessOrder witnessOrder = new VideoWitnessOrder();
		VwCustomerInfo customerInfo = new VwCustomerInfo();

		VideoWitnessOrderExample videoWitnessOrderExample = new VideoWitnessOrderExample();
		videoWitnessOrderExample.createCriteria().andOrderNoEqualTo(
				crmOrderInfo.getReserveNo());
		List<VideoWitnessOrder> listVideoWitnessOrder = videoWitnessOrderMapper
				.selectByExample(videoWitnessOrderExample);

		VideoWitnessOrder videoOrder = null;
		if (listVideoWitnessOrder.size() > 0) {
			videoOrder = listVideoWitnessOrder.get(0);
		}
		witnessOrder.setOrderNo(crmOrderInfo.getReserveNo());
		witnessOrder.setOrderStatus(crmOrderInfo.getOrderStatus());
		witnessOrder.setContractAmount(crmOrderInfo.getBalance());

		if (null != crmOrderInfo.getSubscriptionRatio()
				&& null != crmOrderInfo.getBalance()) {
			witnessOrder.setContractFee(crmOrderInfo.getSubscriptionRatio()
					.multiply(crmOrderInfo.getBalance()));
		}
		witnessOrder.setProjectCode(crmOrderInfo.getSaleProjectNo() + "");
		witnessOrder.setSalesPerson(mapSysUser
				.get(crmOrderInfo.getBrokerCode()).getEmpId());
		witnessOrder.setSalesOrgId(mapSysUser.get(crmOrderInfo.getBrokerCode())
				.getOrgId());

		if (null != crmOrderInfo.getReservationDate()) {
			witnessOrder.setSyncTime(new Timestamp(crmOrderInfo
					.getReservationDate().getTime()));
		}
		witnessOrder
				.setLastOperatorTime(null == crmOrderInfo.getReserveDate() ? new Date()
						: crmOrderInfo.getReserveDate());
		customerInfo.setCustomerNo(crmOrderInfo.getCustNo());
		customerInfo.setIdentityName(crmOrderInfo.getCustName());
		customerInfo.setCustomerType(crmOrderInfo.getCustType());// 客户类型
		customerInfo.setIdentityType(crmOrderInfo.getIdentityType());
		customerInfo.setIdentityCode(crmOrderInfo.getIdentityCode());

		if (null != videoOrder) {
			if (null != crmOrderInfo.getModifyDate()) {
				
				witnessOrder.setOrderId(videoOrder.getOrderId());
				// 更新订单信息
				videoWitnessOrderMapper.updateByPrimaryKeySelective(witnessOrder);
				customerInfo.setCustomerId(videoOrder.getCustomerId());
				customerInfo.setCustomerId(videoOrder.getCustomerId());
				// 更新客户信息
				vwCustomerInfoMapper.updateByPrimaryKeySelective(customerInfo);

			}
			// 如果是已取消、已过期状态，则将预约置为无效
			if (StatusConstants.ORDER_EXPIRE_2.equals(witnessOrder
					.getOrderStatus())
					|| StatusConstants.ORDER_CANCEL_1.equals(witnessOrder
							.getOrderStatus())) {
				
				AppointmentBookingExample appointmentBookingExample = new AppointmentBookingExample();
				appointmentBookingExample.createCriteria()
						.andBizOrderIdEqualTo(videoOrder.getOrderId());
				
				List<AppointmentBooking> listAppointmentBooking = appointmentBookingMapper
						.selectByExample(appointmentBookingExample);
				
				booking = listAppointmentBooking.get(0);
				booking.setIsValid(TypeConstants.INVALID);
				//更新预约信息
				appointmentBookingMapper.updateByPrimaryKeySelective(booking);
			}
			return true;

		} else if(!(StatusConstants.ORDER_EXPIRE_2.equals(witnessOrder
				.getOrderStatus())
				|| StatusConstants.ORDER_CANCEL_1.equals(witnessOrder
						.getOrderStatus()))){
			
			witnessOrder.setOrderSource(TypeConstants.ZR_CRM_SOURCE);
			witnessOrder.setStatus(StatusConstants.WINTNESS_STATE_CREATED);
			witnessOrder.setFlowStatus("0100000000");
			witnessOrder.setIsVip("NO");
			witnessOrder.setVideoStatus(TypeConstants.INVALID);
			booking.setBookNo(appointmentBookingMapper.getBookNo());// 生成预约号
			booking.setBookPwd(StringUtil
					.getRand(Integer.valueOf(ConfigConstants.ORDER_PWD_SIZE)));
			booking.setEffectiveStart(new Date());
			booking.setInitCount(new BigDecimal(
					ConfigConstants.ORDER_INIT_COUNT));
			booking.setLogonCount(new BigDecimal(0));
			booking.setFailCount(new BigDecimal(0));
			booking.setBizSource(TypeConstants.ORDER_BIZ_SOURCE_VIDEO_WITNESS);
			booking.setBlanketApplySource(TypeConstants.ZR_CRM_SOURCE);
			booking.setIsValid(TypeConstants.VALID);
			
			//插入新客户信息
			vwCustomerInfoMapper.insertSelective(customerInfo);

			witnessOrder.setCustomerId(customerInfo.getCustomerId());
			//插入新订单信息
			videoWitnessOrderMapper.insertSelective(witnessOrder);

			booking.setBizOrderId(witnessOrder.getOrderId());
			//插入新预约信息
			appointmentBookingMapper.insertSelective(booking);

			return true;

		}else{
			return false;
		}
	}

	/**
	 * 
	 * TODO 获取系统员工Map （单一返回BaseSysUser） 可以修改返回Object
	 * 
	 * @author 黄瑞庆 Map<String,BaseSysUser>
	 * @return 2017年3月6日 下午2:04:13
	 */
	private static Map<String, BaseSysUser> getSysUserMap(
			List<BaseSysUser> listSysUser) {
		Map<String, BaseSysUser> mapSysUser = new HashMap<String, BaseSysUser>();
		for (BaseSysUser sysUser : listSysUser) {
			mapSysUser.put(sysUser.getEmpNo(), sysUser);
		}
		return mapSysUser;

	}

	public List<CrmOrderInfoV> getRunnableList() {
		return runnableList;
	}

	public void setRunnableList(List<CrmOrderInfoV> runnableList) {
		this.runnableList = runnableList;
	}

	public Map<String, BaseSysUser> getMapSysUser() {
		return mapSysUser;
	}

	public void setMapSysUser(Map<String, BaseSysUser> mapSysUser) {
		this.mapSysUser = mapSysUser;
	}

}
